<?php

namespace app\index\controller;

use app\index\model\Coupon;
use app\index\model\CtmCun;
use app\index\model\Ctmmoneyflow;
use app\index\model\CtmVip;
use app\index\model\ExpercardCustom;
use app\index\model\Item;
use app\index\model\CtmStaff;
use app\index\model\Custom;
use app\index\model\ItemCustom;
use app\index\model\Miaosha;
use app\index\model\MiaoshaCustom;
use app\index\model\Moneyflow;
use app\index\model\Order;
use app\index\model\Servicenews;
use app\index\model\Store;
use app\index\model\Vipcard;
use Predis\Client;
use think\Db;
use think\Queue;
use think\Loader;
use think\Controller;
use app\index\model\Qianggou;
use app\index\model\QianggouCustom;
use app\index\model\UshareCustom;
use app\index\model\Ushare;
use app\util\Utils;

Loader::import('alipay.wappay.service.AlipayTradeService');

/*
 * 支付回调
 */

class AlipayController extends Controller {
    /*
     * H5支付宝回调
     */

    public $config = array(
        //应用ID,您的APPID。
        //'app_id' => "2016091300500454",
        'app_id' => "2017122701271123",
        //商户私钥，您的原始格式RSA私钥
        //'merchant_private_key' => 'MIIEowIBAAKCAQEAzc9dcn80kS5tX9/TIppRYHZmeba0HfK07dpVt8NQghCeFgsbBwxW5AQx4lUoAFoeU0BEEmG/0aWNFRf1FhlCfE/27J1oYzuuErsEnCuf0GH4Vs0foM2ArSLk0Flw964j1isTUQBspWZe1PJijWVYT5BMQsgiflhJvgG2YRMiuhLv9n4UModhNa1MBQw4HRCPXNDp/SXcRZlXRwAcLj0MZGZY8yvxkb5kdU6K70tBkBm5y4pqHBB93ltlQt8U2sY2knW/wqdUPYg2Bh5lrFpn2OTCJrNKYvWABR/A//aqVA5sBM3lnQgW6WA5hRDDZwVuYGYrtEEPXTt3Ah2Qus6s1wIDAQABAoIBABR5pNpXPWuUKt127xJqN95Y6SkCvDiehNGE/zIhBElsTc3znOS+nYZhxHS39BrU3F977UnG38aDqd2HXKKuMKcdbXtszY3Ryiei43qF/IhGtuYr0hG1YC/ZYNo5i7uYX4hXELzmRejOnnChDJz0kCyaNnwOXSAkuHFmyjYuKS5JtiRPmC0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s5O2hALCUY5uI6XxFM6kiauLXt5AHLFqfd6VTmw+zLIx9ThNI4NTc/8oBDZAFaGA5gQbt5WfdsTlFC2cCW0/rEYfGtr2oKlv4e46cmCh0pWNHuEg4yUN28/vA+IzH/aTGD0QHPIQKBgBHeN8kvacXVW6BYIh4hlPPuqn6hMN8x6L0GAkT4KsyMXtH/zj8s+rzb8s4GmY89Tibl58GeOCiKdwEqvhnXr5BJf56TKuHf93OQ+pA8W+dgMzDzdgPLT0zfjSCGrGtZTL7TnPBZ/KDnehqoQt5pACbXZmSQVIWvcEgPCEmT1Vp9AoGBAJ8LGo0wcJz6tweswVV1WnEXub32zJyQozs7lgM9F/+26vIkIkQw3G+BscgRYL8tbWwEnm2c2IFPo+SN57UZbrSsu6cszixoFJr7Hglv3Bsc8TmDShQshGrABG8M26pEhparemDkZ/L5fY4yuATpEHEK5cEluWM8/tFPFpUn4sD3",
        //异步通知地址
        'notify_url' => "http://app.dwkkm.com/kkmtest/public/index/alipay/htmlalipaynotify",
        //同步跳转
        'return_url' => "http://app.dwkkm.com/kkmtest/public/index/alipay/returnurl",
        //编码格式
        'charset' => "UTF-8",
        //签名方式
        'sign_type' => "RSA2",
        //支付宝网关
        //'gatewayUrl' => "https://openapi.alipaydev.com/gateway.do",
        'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
        //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        //'alipay_public_key' =>"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvTj6CzeZ+VAnZYahhSg/sF3vE5p5wzSh4c1cGiFprBggasxS+39357hUsEOl2ninwGCcZUSCMMC2q5HJvWRq89ULgoV7R0+BsobekGuDwqDiVAv/pkqlAzWqlP8X6rBgGUDJY18//hkyem50cRv8RNVdl0YQ+mh3iBgl9wqNADMCY4jlwDGvvbZ2JQSAjua0u/0oXWd6+jBVQypCAO2aXVO2gJK8dMsWCmQiyh/i0YyKJYj2O+0NGvlSY2CbMQKEYsqLtcXuHKIy0k9PBVXJaT4oBxr8ClCVbB72iAYJKZBysIy5yVG2g0RcIrNNJ9Wp3mYHItB7neQbhkI0LhIBRwIDAQAB",
        'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp2rlaJi6lSdjF3GLC8D3m+EYS7ppPMEEvNzzvFrnCdeTdtltkCH6SOrGG5BntYqI6bnOwsv0DqlcGfA4YYvWjZ0UWj4KzUDwW3WEWJh/dKvT5a83gAPzd8TazMPxuxDN3JmSb7pVEe3vxHDY9DUU6F/gJxcvjAjU5BxgQ5wBejJxt4MzjaDQcBC/dhqIswSEJ8kbZupiIMC3Ci1pCgpIma3kyO2rjaH5E2D6ffZL3rCJDYse9PuevcMMqkK9GaQSp/1A2wx2E5o/wYLsTD4+6FWNAGSfJKjvZHSRXegfLP5+jymLTeOyVwj+wx/oUwKwgp8iDFA6cikRQ2Zv+L3iZwIDAQAB",
    );

    public function htmlalipayNotify() {
        $responseData = $_POST;
        $alipaySevice = new \AlipayTradeService($this->config);
        $result = $alipaySevice->check($responseData);
        //支付宝付款回调

        if ($result) {

            if ($responseData['trade_status'] == 'TRADE_SUCCESS') {
                //付款成功
                $body = $responseData['body']; //商户订单号
                $out_trade_no = $responseData['out_trade_no']; //商户订单号
                $total_amount = $responseData['total_amount']; //订单金额
                $trade_no = $responseData['trade_no']; //支付宝订单号

                //防止重复请求
                $predis = new Client();
                $mode = config('appconfig.app_production');
                if ($mode) {
                    $predis->select(1);
                }
                $key = 'order_' . $out_trade_no;
                $exists = $predis->exists($key);
                if ($exists) {
                    return;
                }
                $predis->set($key, $out_trade_no);

                $type = substr($out_trade_no, 0, 1);
                if ($type == Order::TYPE_1) {
                    //商品
                } else if ($type == Order::TYPE_2) {
                    //项目
                    // 写入预约记录如果购买的时候选择了预约时间
                    // 修改订单状态
                    // 修改用户金额
                    // 修改项目销售数量
                    // 修改店铺余额
                    // 写入店铺资金流水
                    // 写入项目购买记录如果项目类型为会员特惠区
                    // 回调成功后写入消息
                    //订单信息
                    $orderRow = Order::with('ordPro,custom,store')
                            ->where('ord_num', '=', $out_trade_no)
                            ->field('id, source, store_id, ctm_id, staff_id, starttime, status')
                            ->order('add_time DESC')
                            ->find();

                    if (!is_null($orderRow) && $orderRow['status'] == Order::STATUS_1) {
                        $order_id = $orderRow['id'];
                        $source = $orderRow['source'];
                        $store_id = $orderRow['store_id'];
                        $ctm_id = $orderRow['ctm_id'];
                        $staff_id = $orderRow['staff_id'];
                        $starttime = $orderRow['starttime'];

                        //订单产品信息
                        $pro_id = $orderRow['ord_pro']['pro_id'];
                        $number = $orderRow['ord_pro']['number'];
                        $item_type = $orderRow['ord_pro']['item_type'];

                        //用户信息
                        $custom_phone = $orderRow['custom']['custom_phone'];
                        $custom_name = $orderRow['custom']['custom_name'];
                        $consume_money = $orderRow['custom']['consume_money'];

                        //店铺信息
                        $store_money = $orderRow['store']['money'];


                        Db::startTrans();

                        $time = time();
                        $flow_number = $custom_phone . $time . mt_rand(1000, 9999);

                        //写入预约记录如果购买的时候选择了预约时间
                        $last_yuyue_id = 0;
                        if ($staff_id == 0) {
                            $ctm_staff_insert_result = true;
                        } else {
                            $ctm_name = strlen($custom_name) > 0 ? $custom_name : $custom_phone;

                            $ctm_staff_insert_result = CtmStaff::insertGetId([
                                        'staff_id' => $staff_id,
                                        'ctm_id' => $ctm_id,
                                        'item_id' => $pro_id,
                                        'store_id' => $store_id,
                                        'order_id' => $order_id,
                                        'number' => 1,
                                        'ctm_name' => $ctm_name,
                                        'ctm_phone' => $custom_phone,
                                        'status' => Order::STATUS_3,
                                        'add_time' => $time,
                                        'start_time' => $starttime,
                            ]);

                            $last_yuyue_id = $ctm_staff_insert_result;
                        }

                        //修改订单状态
                        $status = Order::STATUS_2;
                        if ($staff_id != 0) {
                            if ($number == 1) {
                                $status = Order::STATUS_3;
                            }
                        }
                        $order_status_result = Order::where('id', '=', $order_id)->update([
                            'ordtype' => Order::ORDTYPE_6,
                            'status' => $status,
                            'pay_time' => $time,
                            'update_time' => $time,
                            'alipay_trade_no' => $trade_no,
                        ]);

                        //修改用户金额
                        $consume_money = bcadd($consume_money, $total_amount, 2);
                        $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                            'consume_money' => $consume_money,
                        ]);

                        //修改项目销售数量
                        $item_update_result = Item::where('id', '=', $pro_id)->setInc('sell_count', $number);

                        //修改店铺余额
                        /*
                        $new_store_money = bcadd($store_money, $total_amount, 2);
                        $store_money_result = Store::where('id', '=', $store_id)->update([
                            'money' => $new_store_money,
                        ]);
                        */
                        $store_money_result = Db::execute("UPDATE da_store SET money = money + {$total_amount} WHERE id = {$store_id}");

                        //写入店铺资金流水
                        /*
                        $flow_last_money = $new_store_money;
                        $flow_insert_result = Moneyflow::insert([
                                    'type' => Moneyflow::TYPE_1,
                                    'pro_type' => Moneyflow::PRO_TYPE_2,
                                    'pay_method' => Moneyflow::PAY_METHOD_6,
                                    'store_id' => $store_id,
                                    'staff_id' => 0,
                                    'ctm_id' => $ctm_id,
                                    'money' => $total_amount,
                                    'last_money' => $flow_last_money,
                                    'flow_number' => $flow_number,
                                    'add_time' => $time,
                        ]);
                        */
                        $flow_type = Moneyflow::TYPE_1;
                        $flow_pro_type = Moneyflow::PRO_TYPE_2;
                        $flow_pay_method = Moneyflow::PAY_METHOD_6;
                        $flow_insert_result = Db::execute("INSERT INTO da_moneyflow (type, source, pro_type, pay_method, store_id, staff_id, ctm_id, money, last_money, flow_number, add_time) VALUES ({$flow_type}, {$source}, {$flow_pro_type}, {$flow_pay_method}, {$store_id}, 0, {$ctm_id}, {$total_amount}, (SELECT money FROM da_store WHERE id = {$store_id}), {$flow_number}, {$time})");

                        //写入项目购买记录如果项目类型为会员特惠区
                        if ($item_type == 3) {
                            $item_custom_insert_result = ItemCustom::insert([
                                        'store_id' => $store_id,
                                        'item_id' => $pro_id,
                                        'custom_id' => $ctm_id,
                                        'number' => $number,
                                        'price' => $total_amount,
                                        'add_time' => $time,
                            ]);
                        } else {
                            $item_custom_insert_result = true;
                        }

                        if ($ctm_staff_insert_result && $order_status_result && $custom_money_result && $item_update_result && $store_money_result && $flow_insert_result && $item_custom_insert_result) {
                            Db::commit();

                            //订单消息--已付款
                            $data = [
                                Servicenews::TITLEID_1 => [
                                    'order_id' => $order_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                            //收入消息
                            $data = [
                                Servicenews::TITLEID_10 => [
                                    'order_id' => $order_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                            if ($staff_id != 0) {
                                //预约消息--老板
                                $data = [
                                    Servicenews::TITLEID_2 => [
                                        'order_id' => $order_id,
                                        'staff_type' => 1,
                                        'yuyue_id' => $last_yuyue_id,
                                    ]
                                ];
                                Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                                //预约消息--美容师
                                $data = [
                                    Servicenews::TITLEID_2 => [
                                        'order_id' => $order_id,
                                        'staff_type' => 2,
                                        'yuyue_id' => $last_yuyue_id,
                                    ]
                                ];
                                Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);
                            }
                        } else {
                            Db::rollback();
                        }
                    }
                } else if ($type == Order::TYPE_3) {
                    
                } else if ($type == Order::TYPE_4) {
                    //体验卡
                    // 修改订单状态
                    // 修改用户金额
                    // 写入体验卡购买记录
                    // 修改店铺余额
                    // 写入店铺资金流水
                    // 回调成功后写入消息
                    //订单信息
                    $orderRow = Order::with('ordPro,custom,store')
                            ->where('ord_num', '=', $out_trade_no)
                            ->field('id, source, store_id, ctm_id, staff_id, starttime, status')
                            ->order('add_time DESC')
                            ->find();

                    if (!is_null($orderRow) && $orderRow['status'] == Order::STATUS_1) {
                        $order_id = $orderRow['id'];
                        $source = $orderRow['source'];
                        $store_id = $orderRow['store_id'];
                        $ctm_id = $orderRow['ctm_id'];

                        //订单产品信息
                        $pro_id = $orderRow['ord_pro']['pro_id'];
                        $number = $orderRow['ord_pro']['number'];

                        //用户信息
                        $custom_phone = $orderRow['custom']['custom_phone'];
                        $custom_name = $orderRow['custom']['custom_name'];
                        $consume_money = $orderRow['custom']['consume_money'];

                        //店铺信息
                        $store_money = $orderRow['store']['money'];


                        Db::startTrans();

                        $time = time();
                        $flow_number = $custom_phone . $time . mt_rand(1000, 9999);

                        //修改订单状态
                        $order_status_result = Order::where('id', '=', $order_id)->update([
                            'ordtype' => Order::ORDTYPE_6,
                            'status' => Order::STATUS_2,
                            'pay_time' => $time,
                            'update_time' => $time,
                            'alipay_trade_no' => $trade_no,
                        ]);

                        //修改用户金额
                        $consume_money = bcadd($consume_money, $total_amount, 2);
                        $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                            'consume_money' => $consume_money,
                        ]);

                        //写入体验卡购买记录
                        $start_time = $time;
                        $end_time = $start_time + 31 * 24 * 3600;
                        $expercard_custom_insert_result = ExpercardCustom::insert([
                                    'store_id' => $store_id,
                                    'expercard_id' => $pro_id,
                                    'custom_id' => $ctm_id,
                                    'price' => $total_amount,
                                    'start_time' => $start_time,
                                    'end_time' => $end_time,
                                    'add_time' => $start_time,
                        ]);

                        //修改店铺余额
                        /*
                        $new_store_money = bcadd($store_money, $total_amount, 2);
                        $store_money_result = Store::where('id', '=', $store_id)->update([
                            'money' => $new_store_money,
                        ]);
                        */
                        $store_money_result = Db::execute("UPDATE da_store SET money = money + {$total_amount} WHERE id = {$store_id}");

                        //写入店铺资金流水
                        /*
                        $flow_last_money = $new_store_money;
                        $flow_insert_result = Moneyflow::insert([
                                    'type' => Moneyflow::TYPE_1,
                                    'pro_type' => Moneyflow::PRO_TYPE_4,
                                    'pay_method' => Moneyflow::PAY_METHOD_6,
                                    'store_id' => $store_id,
                                    'staff_id' => 0,
                                    'ctm_id' => $ctm_id,
                                    'money' => $total_amount,
                                    'last_money' => $flow_last_money,
                                    'flow_number' => $flow_number,
                                    'add_time' => $time,
                        ]);
                        */
                        $flow_type = Moneyflow::TYPE_1;
                        $flow_pro_type = Moneyflow::PRO_TYPE_4;
                        $flow_pay_method = Moneyflow::PAY_METHOD_6;
                        $flow_insert_result = Db::execute("INSERT INTO da_moneyflow (type, source, pro_type, pay_method, store_id, staff_id, ctm_id, money, last_money, flow_number, add_time) VALUES ({$flow_type}, {$source}, {$flow_pro_type}, {$flow_pay_method}, {$store_id}, 0, {$ctm_id}, {$total_amount}, (SELECT money FROM da_store WHERE id = {$store_id}), {$flow_number}, {$time})");

                        if ($order_status_result && $custom_money_result && $expercard_custom_insert_result && $store_money_result && $flow_insert_result) {
                            Db::commit();

                            //订单消息--已付款
                            $data = [
                                Servicenews::TITLEID_1 => [
                                    'order_id' => $order_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                            //收入消息
                            $data = [
                                Servicenews::TITLEID_10 => [
                                    'order_id' => $order_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);
                        } else {
                            Db::rollback();
                        }
                    }
                } else if ($type == Order::TYPE_5) {
                    //限时抢购
                    // 修改订单状态
                    // 修改用户金额
                    // 写入限时抢购购买记录
                    // 修改店铺余额
                    // 写入店铺资金流水
                    // 写入预约记录如果购买的时候选择了预约时间
                    // 回调成功后写入消息
                    //订单信息
                    $orderRow = Order::with('ordPro,custom,store')
                            ->where('ord_num', '=', $out_trade_no)
                            ->field('id, source, store_id, ctm_id, staff_id, starttime, status')
                            ->order('add_time DESC')
                            ->find();

                    if (!is_null($orderRow) && $orderRow['status'] == Order::STATUS_1) {
                        $order_id = $orderRow['id'];
                        $source = $orderRow['source'];
                        $store_id = $orderRow['store_id'];
                        $ctm_id = $orderRow['ctm_id'];
                        $staff_id = $orderRow['staff_id'];
                        $starttime = $orderRow['starttime'];

                        //订单产品信息
                        $pro_id = $orderRow['ord_pro']['pro_id'];
                        $number = $orderRow['ord_pro']['number'];

                        //限时抢购信息
                        $miaoshaRow = Miaosha::where('id', '=', $pro_id)
                                ->field('id, item_id, number, sell_count')
                                ->find();
                        $item_id = $miaoshaRow['item_id'];
                        $miaosha_number = $miaoshaRow['number'];
                        $miaosha_sell_count = $miaoshaRow['sell_count'];

                        //用户信息
                        $custom_phone = $orderRow['custom']['custom_phone'];
                        $custom_name = $orderRow['custom']['custom_name'];
                        $consume_money = $orderRow['custom']['consume_money'];

                        //店铺信息
                        $store_money = $orderRow['store']['money'];

                        //已付款秒杀
                        $pay_number = 0;
                        $orderList = Db::table('da_order')->alias('o')
                            ->join('da_ord_pro op', 'op.ord_id = o.id', 'INNER')
                            ->where('o.status', '>', Order::STATUS_1)
                            ->where('op.type', '=', Order::TYPE_5)
                            ->where('op.pro_id', '=', $pro_id)
                            ->field('op.number')
                            ->order('o.add_time desc')
                            ->select();
                        if (count($orderList) > 0) {
                            foreach ($orderList as $k => $v) {
                                $pay_number = $pay_number + $v['number'];
                            }
                        }


                        Db::startTrans();

                        $time = time();
                        $flow_number = $custom_phone . $time . mt_rand(1000, 9999);

                        //写入预约记录
                        $last_yuyue_id = 0;
                        if ($staff_id == 0) {
                            $ctm_staff_insert_result = true;
                        } else {
                            $ctm_name = strlen($custom_name) > 0 ? $custom_name : $custom_phone;
                            $ctm_staff_insert_result = CtmStaff::insertGetId([
                                        'staff_id' => $staff_id,
                                        'ctm_id' => $ctm_id,
                                        'item_id' => $item_id,
                                        'store_id' => $store_id,
                                        'order_id' => $order_id,
                                        'number' => 1,
                                        'ctm_name' => $ctm_name,
                                        'ctm_phone' => $custom_phone,
                                        'status' => Order::STATUS_3,
                                        'add_time' => $time,
                                        'start_time' => $starttime,
                            ]);

                            $last_yuyue_id = $ctm_staff_insert_result;
                        }
                    }

                    //修改订单状态
                    $status = Order::STATUS_2;
                    if ($staff_id != 0) {
                        if ($number == 1) {
                            $status = Order::STATUS_3;
                        }
                    }
                    $order_status_result = Order::where('id', '=', $order_id)->update([
                        'ordtype' => Order::ORDTYPE_6,
                        'status' => $status,
                        'pay_time' => $time,
                        'update_time' => $time,
                        'alipay_trade_no' => $trade_no,
                    ]);

                    //修改用户金额
                    $consume_money = bcadd($consume_money, $total_amount, 2);
                    $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                        'consume_money' => $consume_money,
                    ]);

                    //写入限时抢购购买记录
                    $miaosha_custom_insert_result = MiaoshaCustom::insert([
                                'store_id' => $store_id,
                                'miaosha_id' => $pro_id,
                                'custom_id' => $ctm_id,
                                'number' => $number,
                                'price' => $total_amount,
                                'add_time' => $time,
                    ]);

                    //修改店铺余额
                    /*
                    $new_store_money = bcadd($store_money, $total_amount, 2);
                    $store_money_result = Store::where('id', '=', $store_id)->update([
                        'money' => $new_store_money,
                    ]);
                    */
                    $store_money_result = Db::execute("UPDATE da_store SET money = money + {$total_amount} WHERE id = {$store_id}");

                    //写入店铺资金流水
                    /*
                    $flow_last_money = $new_store_money;
                    $flow_insert_result = Moneyflow::insert([
                                'type' => Moneyflow::TYPE_1,
                                'pro_type' => Moneyflow::PRO_TYPE_5,
                                'pay_method' => Moneyflow::PAY_METHOD_6,
                                'store_id' => $store_id,
                                'staff_id' => 0,
                                'ctm_id' => $ctm_id,
                                'money' => $total_amount,
                                'last_money' => $flow_last_money,
                                'flow_number' => $flow_number,
                                'add_time' => $time,
                    ]);
                    */
                    $flow_type = Moneyflow::TYPE_1;
                    $flow_pro_type = Moneyflow::PRO_TYPE_5;
                    $flow_pay_method = Moneyflow::PAY_METHOD_6;
                    $flow_insert_result = Db::execute("INSERT INTO da_moneyflow (type, source, pro_type, pay_method, store_id, staff_id, ctm_id, money, last_money, flow_number, add_time) VALUES ({$flow_type}, {$source}, {$flow_pro_type}, {$flow_pay_method}, {$store_id}, 0, {$ctm_id}, {$total_amount}, (SELECT money FROM da_store WHERE id = {$store_id}), {$flow_number}, {$time})");

                    //抢完修改更新时间
                    if (($miaosha_number + $miaosha_sell_count) <= ($pay_number + $number)) {
                        $miaosha_result = Miaosha::where('id', '=', $pro_id)->update([
                            'updated_time' => $time,
                        ]);
                    } else {
                        $miaosha_result = true;
                    }

                    if ($ctm_staff_insert_result && $order_status_result && $custom_money_result && $miaosha_custom_insert_result && $store_money_result && $flow_insert_result && $miaosha_result) {
                        Db::commit();

                        //订单消息--已付款
                        $data = [
                            Servicenews::TITLEID_1 => [
                                'order_id' => $order_id,
                            ]
                        ];
                        Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                        //收入消息
                        $data = [
                            Servicenews::TITLEID_10 => [
                                'order_id' => $order_id,
                            ]
                        ];
                        Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                        if ($staff_id != 0) {
                            //预约消息--老板
                            $data = [
                                Servicenews::TITLEID_2 => [
                                    'order_id' => $order_id,
                                    'staff_type' => 1,
                                    'yuyue_id' => $last_yuyue_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                            //预约消息--美容师
                            $data = [
                                Servicenews::TITLEID_2 => [
                                    'order_id' => $order_id,
                                    'staff_type' => 2,
                                    'yuyue_id' => $last_yuyue_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);
                        }
                    } else {
                        Db::rollback();
                    }
                }else if ($type == Order::TYPE_6) {
                    //限时抢购
                    // 修改订单状态
                    // 修改用户金额
                    // 写入限时抢购购买记录
                    // 修改店铺余额
                    // 写入店铺资金流水
                    // 写入预约记录如果购买的时候选择了预约时间
                    // 回调成功后写入消息
                    //订单信息
                    $orderRow = Order::with('ordPro,custom,store')
                            ->where('ord_num', '=', $out_trade_no)
                            ->field('id,source, store_id, ctm_id, staff_id, starttime, status')
                            ->order('add_time DESC')
                            ->find();

                    if (!is_null($orderRow) && $orderRow['status'] == Order::STATUS_1) {
                        $order_id = $orderRow['id'];
                        $store_id = $orderRow['store_id'];
                        $ctm_id = $orderRow['ctm_id'];
                        $staff_id = $orderRow['staff_id'];
                        $starttime = $orderRow['starttime'];
                        $source = $orderRow['source'];

                        //订单产品信息
                        $pro_id = $orderRow['ord_pro']['pro_id'];
                        $number = $orderRow['ord_pro']['number'];

                        //限时抢购信息
                        $miaoshaRow = Qianggou::where('id', '=', $pro_id)
                                ->field('id, item_id, number, sell_count')
                                ->find();
                        $item_id = $miaoshaRow['item_id'];
                        $miaosha_number = $miaoshaRow['number'];
                        $miaosha_sell_count = $miaoshaRow['sell_count'];

                        //用户信息
                        $custom_phone = $orderRow['custom']['custom_phone'];
                        $custom_name = $orderRow['custom']['custom_name'];
                        $consume_money = $orderRow['custom']['consume_money'];

                        //店铺信息
                        $store_money = $orderRow['store']['money'];


                        Db::startTrans();

                        $time = time();
                        $flow_number = $custom_phone . $time . mt_rand(1000, 9999);

                        //写入预约记录
                        $last_yuyue_id = 0;
                        if ($staff_id == 0) {
                            $ctm_staff_insert_result = true;
                        } else {
                            $ctm_name = strlen($custom_name) > 0 ? $custom_name : $custom_phone;
                            $ctm_staff_insert_result = CtmStaff::insertGetId([
                                        'staff_id' => $staff_id,
                                        'ctm_id' => $ctm_id,
                                        'item_id' => $item_id,
                                        'store_id' => $store_id,
                                        'order_id' => $order_id,
                                        'number' => 1,
                                        'ctm_name' => $ctm_name,
                                        'ctm_phone' => $custom_phone,
                                        'status' => Order::STATUS_3,
                                        'add_time' => $time,
                                        'start_time' => $starttime,
                            ]);

                            $last_yuyue_id = $ctm_staff_insert_result;
                        }
                    }

                    //修改订单状态
                    $status = Order::STATUS_2;
                    if ($staff_id != 0) {
                        if ($number == 1) {
                            $status = Order::STATUS_3;
                        }
                    }
                    $order_status_result = Order::where('id', '=', $order_id)->update([
                        'ordtype' => Order::ORDTYPE_6,
                        'status' => $status,
                        'pay_time' => $time,
                        'update_time' => $time,
                        'alipay_trade_no' => $trade_no,
                    ]);

                    //修改用户金额
                    $consume_money = bcadd($consume_money, $total_amount, 2);
                    $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                        'consume_money' => $consume_money,
                    ]);

                    //写入限时抢购购买记录
                    $miaosha_custom_insert_result = QianggouCustom::insert([
                                'store_id' => $store_id,
                                'qianggou_id' => $pro_id,
                                'item_id'=>$item_id,
                                'custom_id' => $ctm_id,
                                'number' => $number,
                                'price' => $total_amount,
                                'add_time' => $time,
                    ]);

                    //修改店铺余额
                    /*
                    $new_store_money = bcadd($store_money, $total_amount, 2);
                    $store_money_result = Store::where('id', '=', $store_id)->update([
                        'money' => $new_store_money,
                    ]);
                    */
                    $store_money_result = Db::execute("UPDATE da_store SET money = money + {$total_amount} WHERE id = {$store_id}");

                    //写入店铺资金流水
                    /*
                    $flow_last_money = $new_store_money;
                    $flow_insert_result = Moneyflow::insert([
                                'type' => Moneyflow::TYPE_1,
                                'pro_type' => Moneyflow::PRO_TYPE_8,
                                'pay_method' => Moneyflow::PAY_METHOD_6,
                                'store_id' => $store_id,
                                'staff_id' => 0,
                                'ctm_id' => $ctm_id,
                                'money' => $total_amount,
                                'last_money' => $flow_last_money,
                                'flow_number' => $flow_number,
                                'add_time' => $time,
                    ]);
                    */
                    $flow_type = Moneyflow::TYPE_1;
                    $flow_pro_type = Moneyflow::PRO_TYPE_8;
                    $flow_pay_method = Moneyflow::PAY_METHOD_6;
                    $flow_insert_result = Db::execute("INSERT INTO da_moneyflow (type,source, pro_type, pay_method, store_id, staff_id, ctm_id, money, last_money, flow_number, add_time) VALUES ({$flow_type},{$source}, {$flow_pro_type}, {$flow_pay_method}, {$store_id}, 0, {$ctm_id}, {$total_amount}, (SELECT money FROM da_store WHERE id = {$store_id}), {$flow_number}, {$time})");

                    if ($ctm_staff_insert_result && $order_status_result && $custom_money_result && $miaosha_custom_insert_result && $store_money_result && $flow_insert_result) {
                        Db::commit();

                        //订单消息--已付款
                        $data = [
                            Servicenews::TITLEID_1 => [
                                'order_id' => $order_id,
                            ]
                        ];
                        Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                        //收入消息
                        $data = [
                            Servicenews::TITLEID_10 => [
                                'order_id' => $order_id,
                            ]
                        ];
                        Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                        if ($staff_id != 0) {
                            //预约消息--老板
                            $data = [
                                Servicenews::TITLEID_2 => [
                                    'order_id' => $order_id,
                                    'staff_type' => 1,
                                    'yuyue_id' => $last_yuyue_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);

                            //预约消息--美容师
                            $data = [
                                Servicenews::TITLEID_2 => [
                                    'order_id' => $order_id,
                                    'staff_type' => 2,
                                    'yuyue_id' => $last_yuyue_id,
                                ]
                            ];
                            Queue::push('app\job\Queue@sendNotifyMessageFunc', $data, null);
                        }
                    } else {
                        Db::rollback();
                    }
                }

                $predis->del($key);
            }
            echo 'success';
        } else {
            echo 'fail';
        }
    }
    /*支付宝h5支付（优享）*/
    public function htmlusharealipaynotify() {
        $responseData = $_POST;
        $alipaySevice = new \AlipayTradeService($this->config);
        $result = $alipaySevice->check($responseData);
        //支付宝付款回调
         
        if ($result) {

            if ($responseData['trade_status'] == 'TRADE_SUCCESS') {
                //付款成功
                $body = $responseData['body']; //商户订单号
                $out_trade_no = $responseData['out_trade_no']; //商户订单号
                $total_amount = $responseData['total_amount']; //订单金额
                $trade_no = $responseData['trade_no']; //支付宝订单号
                $time=  time();

                $usharecustom=UshareCustom::where('ord_num','=',$out_trade_no)->field('id,ushare_id,store_id,ctm_id')->find();
                $ushare=Ushare::where('id','=',$usharecustom['ushare_id'])->find();
                $itemdata=Item::where('id','=',$ushare['item_id'])->field('item_name')->find();
                $customdata = Custom::where('id', '=', $usharecustom['ctm_id'])
                ->field('custom_phone')
                ->find();

                $data['pay_type']=  Order::ORDTYPE_6;
                $data['pay_time']=  $time;
                $data['alipay_trade_no']=  $trade_no;
                $data['status']=  2;
                $data['start_time']=$time;
                $data['end_time']=$time+$ushare['duration']*3600;
                $saveusharecustom=UshareCustom::where('ord_num','=',$out_trade_no)->update($data);
                //助力成功发送消息
                $store_id=$usharecustom['store_id'];
                $order_id=$usharecustom['id'];
                $content = "您成功发起了【[".$itemdata['item_name']."]】优享助力活动，快去分享给更多好友，更快助力成功~";
                $msgContent = Utils::getColoredString($content);
                $pushContent = Utils::getPushString($content);
                $alias = $customdata['custom_phone'] . $store_id;
                $userid = $usharecustom['ctm_id'];
                Utils::sendServicenews(Servicenews::TITLEID_16, $order_id, 0, $msgContent, $userid, Servicenews::TYPE_2, $store_id, [
                    'title' => '活动消息',
                    'content' => $pushContent,
                    'alias_type' => Servicenews::ALIAS_TYPE_2,
                    'alias' => $alias,
                ]);
            }
            echo 'success';
        } else {
            echo 'fail';
        }
    }

    /*
     * H5支付宝支付同步跳转           
     */

    public function returnUrl() {
        $arr = $_GET;
        $alipaySevice = new \AlipayTradeService($this->config);
        $result = $alipaySevice->check($arr);
        if ($result) {//验证成功
            //商户订单号
            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = htmlspecialchars($_GET['trade_no']);
            $orderRow = Order::with('ordPro,custom,store')
                    ->where('ord_num', '=', $out_trade_no)
                    ->field('id, store_id, ctm_id, staff_id, starttime, status')
                    ->order('add_time DESC')
                    ->find();
            if ($orderRow['status'] > 1) {
                $this->redirect("http://app.dwkkm.com/kkmtest/public/v300/h5/paysuccess/order_id/" . $orderRow['id'], 5, '页面跳转中...');
            } else {
                $this->redirect("http://app.dwkkm.com/kkmtest/public/v300/h5/payerror/order_id/" . $orderRow['id'], 5, '页面跳转中...');
            }

            echo "验证成功<br />外部订单号：" . $out_trade_no;
        } else {
            //验证失败
            echo "验证失败";
        }
    }
    
    /*
     * H5支付宝支付同步跳转（优享）           
     */

    public function usharereturnurl() {
        $arr = $_GET;
        $alipaySevice = new \AlipayTradeService($this->config);
        $result = $alipaySevice->check($arr);
        if ($result) {//验证成功
            //商户订单号
            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = htmlspecialchars($_GET['trade_no']);
            $orderRow=UshareCustom::where('ord_num','=',$out_trade_no)->find();
            $usharedata = Ushare::where('id','=',$orderRow['ushare_id'])->field('type')->find();
            $type = $usharedata['type'];
            if ($orderRow['status'] > 1) {
                if($type == 1){
                    $this->redirect("http://app.dwkkm.com/kkmtest/public/v300/h5/usharepaysuccess/order_id/" . $orderRow['id'], 5, '页面跳转中...');
                 }elseif ($type == 2) {
                    $this->redirect("http://app.dwkkm.com/kkmtest/public/v300/h5/motherusharepaySuccess/order_id/" . $orderRow['id'], 5, '页面跳转中...');
                 }
            } else {
                $this->redirect("http://app.dwkkm.com/kkmtest/public/v300/h5/usharepayerror/order_id/" . $orderRow['id'], 5, '页面跳转中...');
            }

            echo "验证成功<br />外部订单号：" . $out_trade_no;
        } else {
            //验证失败
            echo "验证失败";
        }
    }

}
